package site.oldpei.manage.nomal.utils;

import org.apache.commons.lang3.StringUtils;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class XMLUtils {

    public static String getValueByName(Document document, String nodeName) {
        if (document == null || StringUtils.isBlank(nodeName)) {
            return null;
        }
        NodeList genres = document.getElementsByTagName(nodeName);
        if (genres == null || genres.getLength() == 0) {
            return "";
        }
        return genres.item(0).getTextContent();
    }

    public static List<String> getValueListByName(Document document, String nodeName) throws Exception {
        List<String> list = new ArrayList<>();
        if (document == null || StringUtils.isBlank(nodeName)) {
            return list;
        }
        NodeList genres = document.getElementsByTagName(nodeName);
        if (genres == null || genres.getLength() == 0) {
            return list;
        }
        for (int i = 0; i < genres.getLength(); i++) {
            list.add(genres.item(i).getTextContent());
        }
        return list;
    }


    public static void setProperty(Object obj, String propertyName, Object value) throws Exception {
        Class<?> clazz = obj.getClass();
        //防止字段为private时，无法修改字段值的情况
        Field field = clazz.getDeclaredField(propertyName);//暴力反射获取字段
        field.setAccessible(true);//去除权限
        field.set(obj, value);
    }

}
